const app = getApp();
var pageNo = 1;
var pageSize = 10;
var url = app.data.url;
var common = require('../../utils/common.js');
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    order: [],
    selectOrderPopup: false,
    unSubscribeOrderPopup: false,
    itemInfoList: [],
    activeNames: ['1'],
    preNum: '',
    title: "",
    modelId: '4sLRplyItbyfh7G6eD87LcXqe7cidohH8vOdc7uwhQU',
    merchantId: '',
    startTimeShow: false,
    endTimeShow: false,
    beginDayStyle: [{
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#AAD4F5'
      },
      {
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#AAD4F5'
      }
    ],
    outDayStyle: [{
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#84e7d0'
      },
      {
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#84e7d0'
      }
    ],
    beginDateStr: '',
    endDateStr: '',
    dialogShow: false,
    message: '',
    status: '',
    orderItem: ''
  },
  /**
   * 接单或者拒绝确认弹框
   */
  dialogClose: function () {
    let _that = this;
    _that.setData({
      dialogShow: false
    })
  },
  /**
   * 
   */
  onMessageChange: function (event) {
    let _that = this;
    _that.setData({
      message: event.detail
    })
  },
  /**
   * 打电话
   */
  makeCall: function (option) {
    console.log(option);
    let item = option.currentTarget.dataset.item;
    if (!item.phone) {
      wx.showToast({
        title: "当前商家无联系方式",
        icon: "none",
        duration: 2000
      })
      return;
    }
    wx.makePhoneCall({
      phoneNumber: item.phone,
      success: function () {
        console.log("成功拨打电话")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    wx.setNavigationBarTitle({
      title: "我的订单"
    })
    if (!options.merchantId) {
      wx.showToast({
        title: "请先登录!",
        icon: "none",
        duration: 2000
      })
    }
    let _that = this;
    _that.setData({
      merchantId: options.merchantId
    })

  },
  /***
   * 打开dialog 
   */
  openDialog: function (option) {
    let _that = this;
    console.log(option);
    let status = option.currentTarget.dataset.status;
    let item = option.currentTarget.dataset.item;
    _that.setData({
      dialogShow: true,
      status: status,
      orderItem: item
    })
  },
  /**
   * 完成订单
   */
  completeStatus: function (options) {
    let _that = this;
    let orderId = options.currentTarget.dataset.id;
    let status = options.currentTarget.dataset.status;
    wx.request({
      url: url + '/OrderSystemApi/completeOrder',
      data: {
        orderId: orderId,
        status: status
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          Toast.success('操作成功!');
          _that.queryTable(pageNo, pageSize, _that.data.merchantId, false, _that.data.beginDateStr, _that.data.endDateStr);
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },
  /***回复订单 */
  updateRecallStatus: function (option) {
    let _that = this;
    let orderId = _that.data.orderItem.orderId;
    let id = _that.data.orderItem.id;
    let cUuid = _that.data.orderItem.createUserName;
    let msg = _that.data.message;
    wx.request({
      url: url + '/OrderSystemApi/updateMessage',
      data: {
        orderId: id,
        msg: msg
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log("更新msg成功");
        console.log(res);
        // 发送订阅消息
        wx.request({
          url: url + '/WeChatPayApi/toSendReceiveMessage',
          data: {
            orderId: orderId,
            wxUserUuid: cUuid
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (e) {
            if (e.data.code == 200) {
              console.log("发送订阅消息:");
              _that.queryTable(pageNo, pageSize, _that.data.merchantId, false, _that.data.beginDateStr, _that.data.endDateStr);
            } else {
              console.log("发送通知失败");
            }
          }
        })
        _that.setData({
          dialogShow: false
        })
      }
    })
  },
  /**
   * 修改订单状态
   */
  updateStatus: function (options) {
    let _that = this;
    console.log(_that.data.orderItem);
    let orderId = _that.data.orderItem.orderId;
    let id = _that.data.orderItem.id;
    let cUuid = _that.data.orderItem.createUserName;
    let status = _that.data.status;
    let mchid = _that.data.orderItem.merchantId;
    let totalFee = _that.data.orderItem.orderTotalPrice;
    let msg = _that.data.message;
    if (status == '8') {
      if (msg == '') {
        wx.showToast({
          title: "请输入拒绝接单原因",
          icon: "none",
          duration: 2000
        })
        return;
      }
      // 退款再修改状态
      wx.request({
        url: url + '/OrderSystemApi/updateMessage',
        data: {
          orderId: id,
          msg: msg
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function (e) {
          console.log("更新msg成功");
          wx.request({
            url: url + '/WeChatPayApi/refund',
            data: {
              orderId: orderId,
              cUuid: cUuid,
              merchantId: mchid,
              totalFee: totalFee,
              invoking: 1
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              if (res.data.code == 200) {
                // 重新加载列表
                Toast.success('操作成功!');
                // 发送订阅消息
                wx.request({
                  url: url + '/WeChatPayApi/toSendReceiveMessage',
                  data: {
                    orderId: orderId,
                    wxUserUuid: _that.data.orderItem.createUserName
                  },
                  method: 'POST',
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  success: function (e) {
                    console.log("发送订阅消息:");
                    console.log(e);
                  }
                })
                _that.queryTable(pageNo, pageSize, _that.data.merchantId, false, _that.data.beginDateStr, _that.data.endDateStr);
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000
                })
              }
            },
            fail: function (res) {
              console.info('submit fail');
            },
            complete: function (res) {
              console.info('submit complete');
            }
          })
          _that.setData({
            dialogShow: false
          })
        }
      })
    } else {
      wx.request({
        url: url + '/OrderSystemApi/updateMessage',
        data: {
          orderId: id,
          msg: msg
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function (e) {
          console.log("更新msg成功");
          wx.request({
            url: url + '/OrderSystemApi/updateOrderStatusByOrderId',
            data: {
              orderId: orderId,
              status: status
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res);
              if (res.data.code == 200) {
                Toast.success('操作成功!');
                // 发送订阅消息
                if (status == 2) {
                  wx.request({
                    url: url + '/WeChatPayApi/toSendReceiveMessage',
                    data: {
                      orderId: orderId,
                      wxUserUuid: res.data.data
                    },
                    method: 'POST',
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    success: function (e) {
                      console.log("发送订阅消息:");
                      console.log(e);
                    }
                  })

                  // 成功接单, 打印小票
                  wx.request({
                    url: url + '/PrintApi/print',
                    data: {
                      orderId: orderId,
                      merchantId: mchid
                    },
                    method: 'POST',
                    header: {
                      'content-type': 'application/json'
                    }
                  })
                }
                _that.queryTable(pageNo, pageSize, _that.data.merchantId, false, _that.data.beginDateStr, _that.data.endDateStr);
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000
                })
              }
            },
            fail: function (res) {
              console.info('submit fail');
            },
            complete: function (res) {
              console.info('submit complete');
            }
          })
          _that.setData({
            dialogShow: false
          })
        }
      })

    }



  },

  /**导航 */
  location: function (option) {
    let name = option.currentTarget.dataset.merchantname;
    let lat = option.currentTarget.dataset.lat;
    let lot = option.currentTarget.dataset.lot;
    let addr = option.currentTarget.dataset.address;
    console.log(lat);
    console.log(lot);
    //使用后台维护的腾讯服务经纬度(火星坐标系)
    wx.openLocation({
      longitude: Number(lot),
      latitude: Number(lat),
      name: name,
      address: addr
    })
  },

  /**
   * 查询订单
   */
  selectOrder: function (option) {
    var orderId = option.currentTarget.dataset.id;
    let queryType = option.currentTarget.dataset.querytype;
    var that = this;
    wx.navigateTo({
      url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + queryType,
    })

  },
  onCloseSelect() {
    this.setData({
      selectOrderPopup: false
    });
  },
  onChange: function (event) {
    this.setData({
      activeNames: event.detail
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  confirmBeginDate: function () {
    let _that = this;
    let str = _that.data.beginDateStr;
    if (!str) {
      wx.showToast({
        title: "请选择查询开始时间",
        icon: "none",
        duration: 2000
      })
      return;
    }
    _that.setData({
      startTimeShow: false
    });
  },
  confirmEndDate: function () {
    let _that = this;
    let str = _that.data.endDateStr;
    if (!str) {
      wx.showToast({
        title: "请选择查询结束时间",
        icon: "none",
        duration: 2000
      })
      return;
    }
    _that.setData({
      endTimeShow: false
    });
  },
  emptyBeginTime: function (options) {
    let _that = this;
    _that.setData({
      beginDateStr: ''
    })
  },
  emptyEndTime: function (options) {
    let _that = this;
    _that.setData({
      endDateStr: ''
    })
  },
  inDayClick: function (event) {
    let clickDay = event.detail.day;
    let changeDay = `beginDayStyle[1].day`;
    let changeBg = `beginDayStyle[1].background`;
    let year = event.detail.year;
    let month = event.detail.month;
    month = month < 10 ? ('0' + month) : month;
    let day = event.detail.day;
    day = day < 10 ? ('0' + day) : day;
    let str = year + "-" + month + "-" + day;
    this.setData({
      [changeDay]: clickDay,
      [changeBg]: "#FFdd55",
      beginDateStr: str
    })
  },
  outDayClick: function (event) {
    let clickDay = event.detail.day;
    let changeDay = `outDayStyle[1].day`;
    let changeBg = `outDayStyle[1].background`;
    let year = event.detail.year;
    let month = event.detail.month;
    month = month < 10 ? ('0' + month) : month;
    let day = event.detail.day;
    day = day < 10 ? ('0' + day) : day;
    let str = year + "-" + month + "-" + day;
    this.setData({
      [changeDay]: clickDay,
      [changeBg]: "#FFdd55",
      endDateStr: str
    })
  },

  /**
   * 打开查询开始时间日历
   */
  openBeginDate: function (options) {
    let _that = this;
    _that.setData({
      startTimeShow: true
    });
  },
  closeBeginDate: function () {
    let _that = this;
    _that.setData({
      startTimeShow: false
    });
  },
  /**
   * 打开查询结束时间日历
   */
  openOutDate: function (options) {
    let _that = this;
    _that.setData({
      endTimeShow: true
    });
  },
  closeOutDate: function () {
    let _that = this;
    _that.setData({
      endTimeShow: false
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    pageNo = 1;
    that.queryTable(pageNo, pageSize, that.data.merchantId, false, that.data.beginDateStr, that.data.endDateStr);
  },
  /**
   * 查询订单
   */
  search: function (options) {
    var that = this;
    pageNo = 1;
    that.queryTable(pageNo, pageSize, that.data.merchantId, false, that.data.beginDateStr, that.data.endDateStr);
  },
  //列表搜索通用函数
  queryTable: function (pageNo, pageSize, merchantId, flag, startTime, endTime) {
    var that = this;
    wx.request({
      url: url + '/OrderSystemApi/listPageOrder',
      data: {
        pageNo: pageNo,
        pageSize: pageSize,
        merchantId: merchantId,
        searchStartTime: startTime,
        searchEndTime: endTime
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          if (!flag) {
            that.setData({
              order: res.data.data.pageList
            })
          } else {
            if (res.data.data.pageList.length > 0) {
              that.setData({
                order: that.data.order.concat(res.data.data.pageList)
              })
            }
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    pageNo = 1;
    that.queryTable(pageNo, pageSize, that.data.merchantId, false, that.data.beginDateStr, that.data.endDateStr);
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    pageNo = pageNo + 1;
    var that = this;
    that.queryTable(pageNo, pageSize, that.data.merchantId, true, that.data.beginDateStr, that.data.endDateStr);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})